from django import forms
from django.shortcuts import HttpResponse, render, redirect
from app01 import models

"""
    用户管理
"""


def user_list(request):
    """用户管理"""

    data_list = models.UserInfo.objects.all()
    # for index,value in enumerate(data_list):
    # for item in data_list:
    #     print(item.id,
    #           item.name,
    #           item.account,
    #           item.create_time.strftime('%Y-%m-%d'),
    #           item.get_gender_display(),
    #           item.depart.title
    #           )
        # item.get_gender_display()  django 帮我们弄好的，如果以后是level 等级呢  那么就是 get_level_display()
        # item.depart.title  django 帮我们弄好的，因为  depart = models.ForeignKey ，考虑我们会需要对应的中文数据，item.depart 会直接获取到对应的id与title，所以通过item.depart.title 获取到了部门名称

    return render(request, 'user/list.html', {"data_list": data_list})


def user_add(request):
    """添加用户"""
    if request.method == 'GET':
        """原始做法"""
        context = {
            "gender_choices": models.UserInfo.gender_choices,
            "depart_list": models.Deptartment.objects.all()
        }
        return render(request, 'user/add.html', context)
    # 获取用户post提交过来的数据
    name = request.POST.get('name')
    password = request.POST.get('password')
    age = request.POST.get('age')
    account = request.POST.get('account')
    create_time = request.POST.get('create_time')
    gender = request.POST.get('gender')
    depart_id = request.POST.get('depart_id')
    models.UserInfo.objects.create(name=name, password=password, age=age,
                                   account=account, create_time=create_time, gender=gender, depart_id=depart_id)
    return redirect('/user/list/')


class UserModelForm(forms.ModelForm):
    """定义一个类去继承forms.ModelForm"""
    name = forms.CharField(label='姓名', min_length=2, max_length=25)  # 设置最小字符，最大字符

    class Meta:
        model = models.UserInfo
        fields = ['name', 'password', 'age', 'account',
                  'create_time', 'gender', 'depart']  # 字段名
        # widgets = {
        #     # 标签，控制字段渲染时展示的 类型 样式
        #     "name": forms.TextInput(attrs={"class": "layui-input", "placeholder": "请输入姓名", "lay-verify": "required", "lay-reqtext": "请填写用户名", "lay-affix": "clear"}),
        #     "password": forms.PasswordInput(attrs={"class": "layui-input", "placeholder": "请输入密码", "lay-verify": "required", "lay-reqtext": "请输入密码", "lay-affix": "eye"}),
        #     "age": forms.TextInput(
        #         attrs={"class": "layui-input", "placeholder": "请输入年龄", "lay-verify": "required",
        #                "lay-reqtext": "请输入年龄", "lay-affix": "clear"}),
        #     "account": forms.TextInput(
        #         attrs={"class": "layui-input", "placeholder": "请输入账户余额", "lay-verify": "required",
        #                "lay-reqtext": "请输入账户余额", "lay-affix": "clear"}),
        # }
        # <input type="text" name="create_time" lay-verify="required" class="layui-input" id="ID-laydate-demo" placeholder="请选择入职时间" autocomplete="off" class="layui-input">

    # 执行init时,重新定义父类的init方法
    def __init__(self, *args, **kwargs):
        super(UserModelForm, self).__init__(*args, **kwargs)  # 正确地调用父类的构造函数
        for name, field in self.fields.items():
            field.widget.attrs = {"class": "layui-input", "placeholder": field.label, "lay-affix": "clear",
                                  "autocomplete": "off"}
            if name == 'create_time':
                field.widget.attrs = {"class": "layui-input", "placeholder": field.label, "lay-affix": "clear",
                                      'id': 'LayDate-CreateTime', "autocomplete": "off"}


def user_model_form_add(request):
    """添加用户使用ModelForm组件"""
    if request.method == 'GET':
        form = UserModelForm()
        return render(request, 'user/model_form_add.html', {"form": form})
    # 用户post提交数据，开始数据校验
    form = UserModelForm(data=request.POST)
    if form.is_valid():
        # print(form.cleaned_data)
        # 如果数据校验通过，就会在这里执行
        form.save()  # 数据保存
        return redirect('/user/list/')
    else:
        # 数据校验失败，就会在这里执行
        print(form.errors)
        return render(request, 'user/model_form_add.html', {"form": form})


def user_edit(request, user_id):
    """编辑用户使用ModelForm组件"""
    row_obj = models.UserInfo.objects.filter(id=user_id).first()  # 查询对应数据

    if request.method == 'GET':
        form = UserModelForm(instance=row_obj)  # 让实例等于查询的结果，双向绑定
        return render(request, 'user/edit.html', {"form": form})

    # 开始数据校验
    form = UserModelForm(data=request.POST, instance=row_obj)  # 这样写就是，我拿到对应id的数据，然后使用MoelForm来更新
    if form.is_valid():
        # print(form.cleaned_data)
        # 默认保存的是用户输入的所有数据，如果表里有个特殊字段，我们要写入数据可以 这样
        # form.instance.字段名 = 字段值
        # 如果数据校验通过，就会在这里执行
        form.save()  # 数据保存
        return redirect('/user/list/')
    else:
        # 数据校验失败，就会在这里执行
        print(form.errors)
        return render(request, 'user/edit.html', {"form": form})


def user_delete(request):
    """删除用户"""
    user_id = request.GET.get('user_id')
    models.UserInfo.objects.filter(id=user_id).delete()
    return redirect('/user/list/')
